package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URISyntaxException;

public class Test6 {
    public static void main(String[] args) throws Exception {
        Class cls = Test6.class;
        String packagename = cls.getPackage().getName();
        File dir = new File(Test6.class.getResource(".").toURI());
        File[] subs = dir.listFiles(file -> file.getName().endsWith(".class"));
        for(File sub : subs){
            String filename = sub.getName();
            String classname = filename.substring(0,filename.indexOf("."));
            classname = packagename+"."+classname;
            Class c = Class.forName(classname);
            if (c.isAnnotationPresent(AutoRunClass.class)) {
                Object o = c.newInstance();
                System.out.println(o);
                Method[] methods = c.getDeclaredMethods();
                for (int i = 0; i < methods.length; i++) {
                    if(methods[i].isAnnotationPresent(AutoRunMethod.class) && methods[i].getModifiers() == Modifier.PUBLIC) {
                        System.out.println(methods[i].getName());
                        Method method = c.getDeclaredMethod(methods[i].getName());
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int value = arm.value();
                        for (int j = 0; j < value; j++) {
                            method.invoke(o);
                        }
                    }
                }
            }
        }
    }
}
